<template>
    <view class="page">
        <!-- 顶部背景区域 -->
        <view class="header-bg">
            <image class="bg-image" src="/static/images/settings/bg.jpg" mode="aspectFill"></image>
        </view>

        <!-- 头像编辑区域 -->
        <view class="avatar-box">
            <view class="avatar-container" @tap="chooseAvatar">
                <image :src="userInfo.avatar" mode="aspectFill" class="avatar" />
                <view class="edit-icon">
                    <wd-icon name="camera" size="32rpx" color="#fff" />
                </view>
            </view>
            <text class="avatar-tip">点击更换头像</text>
        </view>

        <!-- 信息卡片 -->
        <view class="info-card">
            <view class="card-title">
                <text>基本信息</text>
            </view>

            <view class="card-content">
                <!-- 昵称 -->
                <view class="form-item" @tap="editNickname">
                    <text class="label">昵称</text>
                    <view class="value-box">
                        <text class="value">{{ userInfo.nickname }}</text>
                        <wd-icon name="arrow-right" size="28rpx" color="#C0C4CC" />
                    </view>
                </view>

                <!-- 用户名 -->
                <view class="form-item" @tap="editUsername">
                    <text class="label">用户名</text>
                    <view class="value-box">
                        <text class="value">{{ userInfo.username }}</text>
                        <wd-icon name="arrow-right" size="28rpx" color="#C0C4CC" />
                    </view>
                </view>

                <!-- 性别 -->
                <wd-picker :columns="genderOptions" label="性别" v-model="userInfo.gender" align-right
                    @confirm="onGenderConfirm" />

                <!-- 生日 -->
                <wd-datetime-picker type="date" v-model="userInfo.birthday" align-right label="生日" :max-date="maxDate"
                    :min-date="minDate" @confirm="onDateConfirm" />
            </view>
        </view>

        <view class="info-card">
            <view class="card-title">
                <text>联系方式</text>
            </view>

            <view class="card-content">
                <!-- 手机号 -->
                <view class="form-item" @tap="editPhone">
                    <text class="label">手机号</text>
                    <view class="value-box">
                        <text class="value">{{ formatPhone(userInfo.phone) }}</text>
                        <wd-icon name="arrow-right" size="28rpx" color="#C0C4CC" />
                    </view>
                </view>

                <!-- 邮箱 -->
                <view class="form-item" @tap="editEmail">
                    <text class="label">邮箱</text>
                    <view class="value-box">
                        <text class="value">{{ userInfo.email }}</text>
                        <wd-icon name="arrow-right" size="28rpx" color="#C0C4CC" />
                    </view>
                </view>
            </view>
        </view>

        <view class="info-card">
            <view class="card-title">
                <text>账号安全</text>
            </view>

            <view class="card-content">
                <!-- 修改密码 -->
                <view class="form-item" @tap="changePassword">
                    <text class="label">修改密码</text>
                    <view class="value-box">
                        <text class="value safe">安全设置</text>
                        <wd-icon name="arrow-right" size="28rpx" color="#C0C4CC" />
                    </view>
                </view>
            </view>
        </view>

        <!-- 退出登录按钮 -->
        <view class="logout-section">
            <wd-button type="primary" custom-class="logout-btn" @click="handleLogout">退出登录</wd-button>
        </view>
    </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import request from '@/utils/request'

// 用户数据
const userInfo = ref({
    avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    nickname: '智能家电爱好者',
    username: 'smart_user2023',
    gender: 1, // 0-未设置 1-男 2-女
    birthday: Date.now() - 1000 * 60 * 60 * 24 * 365 * 28, // 28岁
    phone: '13812345678',
    email: 'smart_user@example.com'
})

// 性别选择
const genderOptions = [
    { value: 0, label: '未知' },
    { value: 1, label: '男' },
    { value: 2, label: '女' }
]
const genderText = computed(() => {
    if (userInfo.value.gender === 0) return '未知'
    if (userInfo.value.gender === 1) return '男'
    if (userInfo.value.gender === 2) return '女'
    return '未设置'
})

// 日期选择
const currentDate = new Date()
const maxDate = currentDate.getTime()
const minDate = new Date(currentDate.getFullYear() - 100, 0, 1).getTime()

// 初始化
onLoad(() => {
    getUserData()
})

onShow(() => {
    getUserData()
})

// 获取用户信息
const getUserData = async () => {
    try {
        const data = await request.get({
            url: '/user/info/info'
        })

        // 处理数据
        if (data) {
            userInfo.value = {
                ...data,
                // 将birth转换为timestamp
                birthday: data.birth ? new Date(data.birth).getTime() : null
            }

            // 确保有默认值
            if (!userInfo.value.avatar) {
                userInfo.value.avatar = '/static/images/default-avatar.png'
            }
            if (!userInfo.value.gender) {
                userInfo.value.gender = 0
            }
        }
    } catch (error) {
        console.error('获取用户信息失败:', error)
        uni.showToast({
            title: '获取用户信息失败',
            icon: 'none'
        })
    }
}

// 更新用户信息
const updateUserData = async (params) => {
    try {
        const result = await request.put({
            url: '/user/info/info',
            data: params
        })

        if (result) {
            uni.showToast({
                title: '更新成功',
                icon: 'success'
            })
            // 重新获取最新数据
            getUserData()
        }
    } catch (error) {
        console.error('更新用户信息失败:', error)
        uni.showToast({
            title: '更新失败',
            icon: 'none'
        })
    }
}

// 格式化手机号
const formatPhone = (phone) => {
    if (!phone) return '未设置'
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 格式化日期
const formatDate = (timestamp) => {
    if (!timestamp) return '未设置'
    const date = new Date(timestamp)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 选择头像
const chooseAvatar = () => {
    uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
            const tempFilePath = res.tempFilePaths[0]

            // 这里可以添加图片上传逻辑，获取到头像URL后更新用户信息
            try {
                // 模拟上传图片成功后获取到URL
                uni.uploadFile({
                    url: 'http://localhost:8080/admin/file/upload', //仅为示例，非真实的接口地址
                    filePath: tempFilePath,
                    name: 'file',
                    success: (uploadFileRes) => {
                        console.log(uploadFileRes.data)
                        const data = JSON.parse(uploadFileRes.data)
                        userInfo.value.avatar = data.data
                        updateUserData({
                            avatar: userInfo.value.avatar
                        })
                    }
                });
            } catch (error) {
                console.error('头像更新失败:', error)
                uni.showToast({
                    title: '头像更新失败',
                    icon: 'none'
                })
            }
        }
    })
}

// 编辑昵称
const editNickname = () => {
    uni.showModal({
        title: '修改昵称',
        content: '',
        editable: true,
        placeholderText: '请输入昵称',
        confirmColor: '#3c78d8',
        confirmText: '确认修改',
        value: userInfo.value.nickname || '',
        success: async (res) => {
            if (res.confirm && res.content.trim()) {
                await updateUserData({
                    nickname: res.content
                })
                userInfo.value.nickname = res.content
            }
        }
    })
}

// 编辑用户名
const editUsername = () => {
    uni.showModal({
        title: '修改用户名',
        content: '',
        editable: true,
        placeholderText: '请输入用户名',
        confirmColor: '#3c78d8',
        confirmText: '确认修改',
        value: userInfo.value.username || '',
        success: async (res) => {
            if (res.confirm && res.content.trim()) {
                await updateUserData({
                    username: res.content
                })
                userInfo.value.username = res.content
            }
        }
    })
}

// 编辑手机号
const editPhone = () => {
    uni.showModal({
        title: '修改手机号',
        content: '',
        editable: true,
        placeholderText: '请输入手机号',
        confirmColor: '#3c78d8',
        confirmText: '确认修改',
        value: userInfo.value.phone || '',
        success: async (res) => {
            if (res.confirm) {
                if (!/^1[3-9]\d{9}$/.test(res.content)) {
                    uni.showToast({
                        title: '手机号格式不正确',
                        icon: 'none'
                    })
                    return
                }
                await updateUserData({
                    phone: res.content
                })
                userInfo.value.phone = res.content
            }
        }
    })
}

// 编辑邮箱
const editEmail = () => {
    uni.showModal({
        title: '修改邮箱',
        content: '',
        editable: true,
        placeholderText: '请输入邮箱',
        confirmColor: '#3c78d8',
        confirmText: '确认修改',
        value: userInfo.value.email || '',
        success: async (res) => {
            if (res.confirm) {
                if (!/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(res.content)) {
                    uni.showToast({
                        title: '邮箱格式不正确',
                        icon: 'none'
                    })
                    return
                }
                await updateUserData({
                    email: res.content
                })
                userInfo.value.email = res.content
            }
        }
    })
}

// 性别选择确认
const onGenderConfirm = async (event) => {
    const gender = event.value
    await updateUserData({
        gender: gender
    })
    userInfo.value.gender = gender
}

// 日期选择确认
const onDateConfirm = async (event) => {
    const birthday = event.value
    // 将时间戳转换为日期字符串 YYYY-MM-DD
    const date = new Date(birthday)
    const birth = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`

    await updateUserData({
        birth: birth
    })
    userInfo.value.birthday = birthday
}

// 修改密码
const changePassword = () => {
    uni.navigateTo({
        url: '/pages/settings/password'
    })
}

// 退出登录
const handleLogout = () => {
    uni.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        confirmColor: '#ff4d4f',
        success: async (res) => {
            if (res.confirm) {
                try {
                    const result = await request.post({
                        url: '/user/info/logout'
                    })

                    if (result) {
                        uni.showToast({
                            title: '退出成功',
                            icon: 'success'
                        })

                        // 清除本地存储的登录信息
                        uni.removeStorageSync('token')
                        uni.removeStorageSync('userInfo')

                        // 跳转到登录页
                        setTimeout(() => {
                            uni.reLaunch({
                                url: '/pages/login/login'
                            })
                        }, 1000)
                    }
                } catch (error) {
                    console.error('退出登录失败:', error)
                    uni.showToast({
                        title: '退出失败',
                        icon: 'none'
                    })
                }
            }
        }
    })
}
</script>

<style lang="scss">
.page {
    min-height: 100vh;
    background: #f8f8f8;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
}

.header-bg {
    position: relative;
    height: 220rpx;
    overflow: hidden;

    .bg-image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1;
    }

    &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 60rpx;
        background: linear-gradient(to bottom, rgba(248, 248, 248, 0), rgba(248, 248, 248, 1));
        z-index: 2;
    }
}

.avatar-box {
    margin-top: -80rpx;
    padding: 0 0 40rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    z-index: 10;

    .avatar-container {
        position: relative;
        width: 160rpx;
        height: 160rpx;
        margin-bottom: 20rpx;

        .avatar {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            border: 6rpx solid #fff;
            box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.1);
        }

        .edit-icon {
            position: absolute;
            right: 6rpx;
            bottom: 6rpx;
            width: 56rpx;
            height: 56rpx;
            background: rgba(0, 0, 0, 0.6);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 3rpx solid #fff;
        }
    }

    .avatar-tip {
        font-size: 24rpx;
        color: #999;
    }
}

.info-card {
    margin: 20rpx 24rpx 30rpx;
    background: #fff;
    border-radius: 12rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .card-title {
        padding: 24rpx;
        border-bottom: 1rpx solid #f5f5f5;

        text {
            font-size: 30rpx;
            font-weight: 600;
            color: #333;
            position: relative;
            padding-left: 20rpx;

            &::before {
                content: '';
                position: absolute;
                left: 0;
                top: 50%;
                transform: translateY(-50%);
                width: 6rpx;
                height: 24rpx;
                background: #3c78d8;
                border-radius: 3rpx;
            }
        }
    }

    .card-content {
        .form-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 28rpx 24rpx;
            position: relative;

            &:not(:last-child)::after {
                content: '';
                position: absolute;
                left: 24rpx;
                right: 24rpx;
                bottom: 0;
                height: 1px;
                background: #f5f5f5;
            }

            .label {
                font-size: 28rpx;
                color: #666;
            }

            .value-box {
                display: flex;
                align-items: center;

                .value {
                    font-size: 28rpx;
                    color: #333;
                    font-weight: 500;
                    margin-right: 8rpx;

                    &.safe {
                        color: #3c78d8;
                    }
                }
            }
        }

        .wd-cell {
            padding: 28rpx 24rpx;

            &::after {
                left: 24rpx;
                right: 24rpx;
            }
        }
    }
}

.logout-section {
    padding: 40rpx 24rpx 50rpx;
    margin-bottom: constant(safe-area-inset-bottom);
    margin-bottom: env(safe-area-inset-bottom);

    .logout-btn {
        width: 100%;
        height: 90rpx;
        border-radius: 45rpx;
        font-size: 32rpx;
        font-weight: 500;
        background: #ff4d4f;
        border: none;
        color: #fff;
        box-shadow: 0 6rpx 16rpx rgba(255, 77, 79, 0.2);

        &::after {
            display: none;
        }
    }
}
</style>